package com.network.retrofit.net.okhttp;

import android.app.Application;


import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.security.KeyStore;
import java.security.SecureRandom;
import java.security.cert.CertificateFactory;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;

import okhttp3.Cache;
import okhttp3.OkHttpClient;

/**
 * 项目: com.network.retrofit.utils
 * 创建人: LuoFG
 * 创建时间: 2021/6/29  14:57
 * 描述:
 */
public class OkHttpUtil {

    private static class OkHttpUtilHolder {
        private static OkHttpUtil instance = new OkHttpUtil();
    }

    public static OkHttpUtil getInstance() {
        return OkHttpUtilHolder.instance;
    }

    public OkHttpClient okHttpClient;

    /**
     * 获取oKHttpClient
     * certificates 证书信息 没有就传null
     *
     * @return
     */
    public OkHttpClient getOkHttpClient(Application application) {
        if (okHttpClient == null) {
            File sdCache = application.getExternalCacheDir();
            int cacheSize = 10 * 1024 * 1024;
            OkHttpClient.Builder builder = new OkHttpClient.Builder()
                    .addNetworkInterceptor(new MyLogInterceptor("OkHttpBack_TAG"))
                    .connectTimeout(20, TimeUnit.SECONDS)
                    .writeTimeout(20, TimeUnit.SECONDS)
                    .readTimeout(20, TimeUnit.SECONDS)
                    //cookie配置
                    //.cookieJar(cookieJar)
                    //配置缓存
                    .cache(new Cache(sdCache.getAbsoluteFile(), cacheSize));

            okHttpClient = builder.build();
        }
        return okHttpClient;
    }


    /**
     * 获取SSLSocketFactory old方法
     *
     * @param certificates 证书流文件
     * @return
     */
    public static SSLSocketFactory getSSLSocketFactory(InputStream... certificates) {
        try {
            CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
            KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
            keyStore.load(null);
            int index = 0;
            for (InputStream certificate : certificates) {
                String certificateAlias = Integer.toString(index++);
                keyStore.setCertificateEntry(certificateAlias, certificateFactory.generateCertificate(certificate));

                try {
                    if (certificate != null) {
                        certificate.close();
                    }
                } catch (IOException e) {
                }
            }
            SSLContext sslContext = SSLContext.getInstance("TLS");
            TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            trustManagerFactory.init(keyStore);
            sslContext.init(null, trustManagerFactory.getTrustManagers(), new SecureRandom());
            return sslContext.getSocketFactory();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * @param builder 构造器
     * @param certificates 证书keystore流文件
     * @param tradeNumber 证书密码
     */
    public static void addSSL(OkHttpClient.Builder builder ,InputStream certificates,String tradeNumber){
        try {
            TrustManagerFactory trustManagerFactory = null;
            trustManagerFactory = TrustManagerFactory.getInstance(
                    TrustManagerFactory.getDefaultAlgorithm());
            trustManagerFactory.init((KeyStore) null);
            TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
            if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) {
                throw new IllegalStateException("Unexpected default trust managers:"
                        + Arrays.toString(trustManagers));
            }
            X509TrustManager trustManager = (X509TrustManager) trustManagers[0];



            KeyStore keystore = KeyStore.getInstance("PKCS12");
            char[] keyPassword = tradeNumber.toCharArray();
            //证书密码
            keystore.load(certificates, keyPassword);
            SSLContext sslContext = SSLContext.getInstance("TLS");
            KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            kmfactory.init(keystore, keyPassword);
            sslContext.init(kmfactory.getKeyManagers(), new TrustManager[]{trustManager}, new SecureRandom());
            SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
            builder.sslSocketFactory(sslSocketFactory, trustManager);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
